package cn.jhc.db;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;









import javax.sql.DataSource;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;





import cn.jhc.bean.Song;
import cn.jhc.bean.User;
import cn.jhc.bean.UserSong;

public class UserDao {
	private static String username="";

	public static String getUsername() {
		return username;
	}

	public static void setUsername(String username) {
		UserDao.username = username;
	}

	public static void addUser(DataSource dataSource,User user) {
		Connection connection = null;
		try {
			
			QueryRunner runner = new QueryRunner(dataSource);
			String sql = "insert into user(username,email,password) values(?,?,?)";
			runner.insert(sql, new BeanHandler<>(User.class),
					user.getUsername(),user.getEmail(),user.getPassword());
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(connection);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static void deleteAll(DataSource dataSource) throws SQLException{
		QueryRunner runner = new QueryRunner(dataSource);
		runner.update("delete from user");
	}

	public static List<User> findAll(DataSource dataSource) {
		List<User> list = null;
		Connection conn= null;	
		try {
			QueryRunner runner =new  QueryRunner(dataSource);

			String sql = "select * from user where username = ?";
			Object[] pamars={username};
			ResultSetHandler<List<User>> h = new BeanListHandler<>(User.class);
			list = runner.query(sql,h,pamars);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}
		
	
}
